var db = require('../model');
var utils = require('../utils');

module.exports = {
  get:function(req,res,next){
    var paging = utils.getPaging(req.query);
    var did = req.query.did;
    db.comment.find({
      related_id:did
    })
    .populate({
      path:'userid',
      model:db.user,
      select:'_id nick avatar profile'
    })
    .sort({created_at:1})
    .skip(paging.skip)
    .limit(paging.count)
    .lean()
    .then(ret => {
      utils.fixUser(ret);
      ret.forEach((item)=>{
        utils.setTime(item);
      });
      res.json(utils.formatResult(ret));
    });
  },
  save:function(req,res,next){
    var content = req.body.content,
        related_id = req.body.related_id,
        userid = req.body.userid,
        replyid = req.body.replyid,
        replyname = req.body.replyname;

    if(req.decoded.data.block == 1){
      return next("您得账号已经被封停，请联系管理员");
    }
    if (content.length <= 0 || content.length > 200) {
      return next("评论内容不能为空或超过220个字节");
    }

    var saveData = {
      content: content,
      related_id: related_id,
      userid: userid,
      created_at:Date.now()
    };

    if (replyid && replyname) {
      saveData['content'] = '@' + replyname + ' ' + content;
    }
    
    db.diary.findOne({_id:related_id}).then((ret)=>{
      if(ret.forbid == 1){
        return next('此日记不允许被评论'); 
      }
      var comment = new db.comment(saveData);
      comment.save(saveData).then((ret)=>{
          db.diary.update({_id:related_id},{
            '$inc':{
              'commentcount':1 
            } 
          }).then();
          db.user.update({_id:userid},{
            '$inc':{
              'tocommentcount':1 
            }
          }).then();
          db.comment.findOne({
            _id:ret._id 
          }).populate({
            path:'userid',
            model:db.user,
            select:'_id nick avatar'
          })
          .lean()
          .then((ret)=>{
            utils.fixUser([ret]);
            utils.setTime(ret);
            res.json(utils.formatResult(ret)); 
          },next);
          //tips
          //if (diarydata.userid !== userid) tuerBase.addDiaryTips(diarydata.userid, diaryid);
          //if (replyid && replyid != userid) tuerBase.addDiaryTips(replyid, diaryid);
      },next);
    })
  },
  remove:function(req,res,next){
    var diaryid = req.body.diaryid,commentid = req.body.commentid,userid = req.decoded.data._id;
    db.comment.find({
      _id:commentid,
      related_id:diaryid,
      userid:userid
    }).remove().then(ret=>{
      res.json(utils.formatResult({status:'success'})); 
      db.diary.update({_id:diaryid},{
        '$inc':{
          'commentcount':-1 
        } 
      }).then();
      db.user.update({_id:userid},{
        '$inc':{
          'tocommentcount':-1 
        }
      }).then();
    },next);
  }
};
